package com.alibaba.citrus.cr.sales.plan.repository;

import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryDepartmentTaskCountRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanScItemStatRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryPlanScItemStatRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanScItemStatSubTotalRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.response.SalesPlanSubTotalResponse;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.request.BatchQueryPlanScItemRequest;
import com.alibaba.citrus.cr.sales.plan.repository.request.StatCategoryQueryRequest;
import com.alibaba.citrus.cr.sales.plan.repository.request.StatOrganizationQueryRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.citrus.cr.sales.plan.converter.PlanScItemConverter;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.epoch.app.bcorder.model.dto.PlanScItemLoadListRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchDeletePlanScItemRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchDeletePlanScItemResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchLoadPlanScItemRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchLoadPlanScItemResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchQueryByBizIdRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchSavePlanScItemRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.BatchSavePlanScItemResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.CreatePlanScItemResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.LoadPlanScItemListRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.LoadPlanScItemRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.PlanCategoryStatRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.PlanCategoryStatResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.PlanOrganizationStatRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.PlanOrganizationStatResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.QueryPlanScItemByPlanIdRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.SubTotalSalesPlanScItemStatRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.SubTotalSalesPlanScItemStatResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.UpdatePlanScItemResponse;
import com.epoch.app.bcorder.sales_plan.planscitem.dto.UpdatePlanScItemStatusRequest;
import com.epoch.app.bcorder.sales_plan.planscitem.model.PlanScItem;
import com.epoch.app.bcorder.sales_plan.planscitem.service.PlanScItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-09-27 11:12
 */
@Component
public class SalesPlanScItemStatRepositoryImpl implements SalesPlanScItemStatRepository {
    Log log =Log.getLogger(SalesPlanScItemStatRepositoryImpl.class);

    @Resource
    PlanScItemService planScItemService;

    @Override
    @RepositoryInvoker
    public String createPlanScItem(SalesPlanStatScItemSDO sdo) {
        CreatePlanScItemResponse planScItem = planScItemService.createPlanScItem(PlanScItemConverter.planScItemSdoToDo(sdo));
        if (planScItem != null) {
            return planScItem.getLastInsertId();
        }
        return null;
    }

    @Override
    @RepositoryInvoker
    public Boolean batchCreatePlanScItem(List<SalesPlanStatScItemSDO> requestList) {
        BatchSavePlanScItemRequest request = new BatchSavePlanScItemRequest();
        request.setRequest(PlanScItemConverter.planScItemSdoToDo(requestList));
        BatchSavePlanScItemResponse batchSavePlanScItemResponse = planScItemService.batchSavePlanScItem(request);
        return batchSavePlanScItemResponse != null && batchSavePlanScItemResponse.getCount() != null && batchSavePlanScItemResponse.getCount() == requestList.size();
    }

    @Override
    @RepositoryInvoker
    public Boolean editSalesPlanScItem(SalesPlanStatScItemSDO salesPlanScItemStatSDO) {
        PlanScItem planScItem = PlanScItemConverter(salesPlanScItemStatSDO);
        try {
            Integer count = planScItemService.updatePlanScItem(planScItem).getCount();
            if (count < 1) {
                log.error("货品:{}更新货品失败", JSONObject.toJSONString(salesPlanScItemStatSDO));
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据更新失败");
        }
        return true;
    }

    @Override
    @RepositoryInvoker
    public Boolean updatePlanScItem(SalesPlanStatScItemSDO salesPlanScItemStatSDO) {
        UpdatePlanScItemResponse updatePlanScItemResponse = planScItemService.updatePlanScItem(PlanScItemConverter.planScItemSdoToDo(salesPlanScItemStatSDO));
        return updatePlanScItemResponse != null && updatePlanScItemResponse.getCount() != null && updatePlanScItemResponse.getCount() > 0;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean updateSalesPlanScItemStatus(SalesPlanStatScItemSDO salesPlanScItemStatSDO) {
        UpdatePlanScItemStatusRequest request = new UpdatePlanScItemStatusRequest();
        request.setIds(salesPlanScItemStatSDO.getIds());
        request.setStatus(salesPlanScItemStatSDO.getStatus());
        try {
            Integer count = planScItemService.updatePlanScItemStatus(request).getCount();
            if (count < 1) {
                log.error("货品:{}批量更新货品失败",JSONObject.toJSONString(salesPlanScItemStatSDO));
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据更新失败");
        }
        return true;
    }

    @Override
    @RepositoryInvoker
    public Boolean deletePlanScItemByPlanId(String planId) {
        BatchDeletePlanScItemRequest request = new BatchDeletePlanScItemRequest();
        request.setPlanId(planId);
        BatchDeletePlanScItemResponse batchDeletePlanScItemResponse = planScItemService.batchDeletePlanScItem(request);
        return batchDeletePlanScItemResponse != null && batchDeletePlanScItemResponse.getCount() != null && batchDeletePlanScItemResponse.getCount() > 0;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<SalesPlanStatScItemSDO>> pageQueryPlanScItemList(PageQueryPlanScItemStatRequest pageQueryPlanScItemStatRequest) {
        LoadPlanScItemListRequest loadPlanScItemListRequest = new LoadPlanScItemListRequest();
        BeanUtils.copyProperties(pageQueryPlanScItemStatRequest,loadPlanScItemListRequest);
        //查询调整数据,调整汇总
        if (pageQueryPlanScItemStatRequest.getIsAdjustCount()) {
            loadPlanScItemListRequest.setAdjustCount(0);
        }
        Result<List<PlanScItem>> listResult = planScItemService.loadPlanScItemList(loadPlanScItemListRequest);
        List<SalesPlanStatScItemSDO> collect = listResult.getResult().stream().map(planScItem -> {
            SalesPlanStatScItemSDO salesPlanStatScItemSDO = new SalesPlanStatScItemSDO();
            BeanUtils.copyProperties(planScItem, salesPlanStatScItemSDO);
            salesPlanStatScItemSDO.setPlanId(String.valueOf(planScItem.getPlanId()));
            return salesPlanStatScItemSDO;
        }).collect(Collectors.toList());
        return PageResult.of(collect, listResult.getTotal());
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<SalesPlanStatScItemSDO>> queryDepartmentTaskCountList(
        PageQueryDepartmentTaskCountRequest queryDepartmentTaskCount) {
        PageQueryPlanScItemStatRequest queryPlanScItemStatRequest = new PageQueryPlanScItemStatRequest();
        BeanUtils.copyProperties(queryDepartmentTaskCount, queryPlanScItemStatRequest);
        queryPlanScItemStatRequest.setBizType(SalesStatBizTypeEnum.SALES_DEPARTMENT.getBizType());
        return this.pageQueryPlanScItemList(queryPlanScItemStatRequest);
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<SalesPlanStatScItemSDO>> batchQueryPlanScItemByBizId(
        QueryPlanScItemStatRequest queryPlanScItemStatRequest) {
        BatchQueryByBizIdRequest batchQueryByBizIdRequest = new BatchQueryByBizIdRequest();
        BeanUtils.copyProperties(queryPlanScItemStatRequest, batchQueryByBizIdRequest);
        batchQueryByBizIdRequest.setPlanId(Objects.toString(queryPlanScItemStatRequest.getPlanId(), null));
        batchQueryByBizIdRequest.setBizType(Objects.toString(queryPlanScItemStatRequest.getBizType(), null));
        Result<List<PlanScItem>> scItemList = planScItemService.batchQueryByBizId(batchQueryByBizIdRequest);
        List<SalesPlanStatScItemSDO> resultList = scItemList.getResult().stream().map(scItem -> {
            SalesPlanStatScItemSDO scItemStatSDO = new SalesPlanStatScItemSDO();
            BeanUtils.copyProperties(scItem, scItemStatSDO);
            scItemStatSDO.setPlanId(String.valueOf(scItem.getPlanId()));
            return scItemStatSDO;
        }).collect(Collectors.toList());
        return PageResult.of(resultList, scItemList.getTotal());
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public List<SalesPlanStatScItemSDO> queryPlanScItemByPlanId(QueryPlanScItemStatRequest queryPlanScItemStatRequest) {
        QueryPlanScItemByPlanIdRequest queryPlanScItemByPlanIdRequest = queryPlanScItemStatRequestConverter(queryPlanScItemStatRequest);
        List<PlanScItem> planScItemList = planScItemService.queryPlanScItemByPlanId(queryPlanScItemByPlanIdRequest).getResult();
        List<SalesPlanStatScItemSDO> salesPlanScItemStatSDOList = planScItemList.stream().map(scItem -> {
            SalesPlanStatScItemSDO salesPlanScItemStatSDO = new SalesPlanStatScItemSDO();
            BeanUtils.copyProperties(scItem, salesPlanScItemStatSDO);
            return salesPlanScItemStatSDO;
        }).collect(Collectors.toList());
        return salesPlanScItemStatSDOList;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public SalesPlanStatScItemSDO getSalesPlanScItem(QueryPlanScItemStatRequest queryPlanScItemStatRequest) {
        LoadPlanScItemRequest loadPlanScItemRequest = loadPlanScItemRequestConverter(queryPlanScItemStatRequest);
        PlanScItem planScItem = planScItemService.loadPlanScItem(loadPlanScItemRequest);
        SalesPlanStatScItemSDO salesPlanScItemStatSDO = new SalesPlanStatScItemSDO();
        BeanUtils.copyProperties(planScItem, salesPlanScItemStatSDO);
        salesPlanScItemStatSDO.setPlanId(String.valueOf(planScItem.getPlanId()));
        return salesPlanScItemStatSDO;
    }

    @Override
    @RepositoryInvoker
    public List<SalesPlanStatScItemSDO> batchQueryPlanScItem(BatchQueryPlanScItemRequest request) {
        BatchLoadPlanScItemRequest build = BatchLoadPlanScItemRequest.builder()
                .planId(request.getPlanId())
                .scItemId(request.getScItemId())
                .build();
        BatchLoadPlanScItemResponse batchLoadPlanScItemResponse = planScItemService.batchLoadPlanScItem(build);
        if (batchLoadPlanScItemResponse == null || CollectionUtils.isEmpty(batchLoadPlanScItemResponse.getResult())) {
            return null;
        }
        return PlanScItemConverter.planScItemDoToSdo(batchLoadPlanScItemResponse.getResult());
    }

    @Override
    @RepositoryInvoker
    public List<SalesPlanStatScItemSDO> statOrganization(StatOrganizationQueryRequest statQueryRequest) {
        PlanOrganizationStatRequest request = new PlanOrganizationStatRequest();
        request.setPlanId(statQueryRequest.getPlanId());
        request.setPoolType(statQueryRequest.getPoolType());
        request.setBizType(statQueryRequest.getBizType());
        request.setStart(statQueryRequest.getStart());
        request.setLimit(statQueryRequest.getLimit());
        PlanOrganizationStatResponse planOrganizationStatResponse = planScItemService.planOrganizationStat(request);
        if (planOrganizationStatResponse == null) {
            return null;
        }
        return PlanScItemConverter.planScItemDoToSdo(planOrganizationStatResponse.getResult());
    }

    @Override
    @RepositoryInvoker
    public List<SalesPlanStatScItemSDO> statCategory(StatCategoryQueryRequest statQueryRequest) {
        PlanCategoryStatRequest request = new PlanCategoryStatRequest();
        request.setPlanId(statQueryRequest.getPlanId());
        request.setPoolType(statQueryRequest.getPoolType());
        request.setBizType(statQueryRequest.getBizType());
        request.setStrat(statQueryRequest.getStart());
        request.setLimit(statQueryRequest.getLimit());
        PlanCategoryStatResponse planCategoryStatResponse = planScItemService.planCategoryStat(request);
        if (planCategoryStatResponse == null) {
            return null;
        }
        return PlanScItemConverter.planScItemDoToSdo(planCategoryStatResponse.getResult());
    }

    @Override
    @RepositoryInvoker
    public SalesPlanSubTotalResponse subTotalSalesPlanScItemStat(SalesPlanScItemStatSubTotalRequest salesPlanScItemStatSubTotalRequest) {
        SubTotalSalesPlanScItemStatRequest statQueryRequest = new SubTotalSalesPlanScItemStatRequest();
        BeanUtils.copyProperties(salesPlanScItemStatSubTotalRequest, statQueryRequest);
        statQueryRequest.setPlanId(Long.valueOf(salesPlanScItemStatSubTotalRequest.getPlanId()));
        //查询调整数据
        if (salesPlanScItemStatSubTotalRequest.getIsAdjustCount()) {
            statQueryRequest.setAdjustCount(0);
        }
        SubTotalSalesPlanScItemStatResponse subTotalStatResponse = planScItemService.subTotalSalesPlanScItemStat(statQueryRequest);
        SalesPlanSubTotalResponse salesPlanSubTotalResponse = SalesPlanSubTotalResponse.builder().build();
        BeanUtils.copyProperties(subTotalStatResponse, salesPlanSubTotalResponse);
        salesPlanSubTotalResponse.setPlanId(statQueryRequest.getPlanId());
        return salesPlanSubTotalResponse;
    }

    private QueryPlanScItemByPlanIdRequest queryPlanScItemStatRequestConverter(QueryPlanScItemStatRequest queryPlanScItemStatRequest) {
        QueryPlanScItemByPlanIdRequest queryPlanScItemByPlanIdRequest = new QueryPlanScItemByPlanIdRequest();
        BeanUtils.copyProperties(queryPlanScItemStatRequest, queryPlanScItemByPlanIdRequest);
        queryPlanScItemByPlanIdRequest.setPlanId(String.valueOf(queryPlanScItemStatRequest.getPlanId()));
        return queryPlanScItemByPlanIdRequest;
    }

    private LoadPlanScItemRequest loadPlanScItemRequestConverter(QueryPlanScItemStatRequest queryPlanScItemStatRequest) {
        LoadPlanScItemRequest loadPlanScItemRequest = new LoadPlanScItemRequest();
        BeanUtils.copyProperties(queryPlanScItemStatRequest, loadPlanScItemRequest);
        loadPlanScItemRequest.setId(Optional.ofNullable(queryPlanScItemStatRequest.getId()).map(Long::parseLong).orElse(null));
        return loadPlanScItemRequest;
    }

    private PlanScItem PlanScItemConverter(SalesPlanStatScItemSDO salesPlanScItemStatSDO) {
        PlanScItem planScItem = new PlanScItem();
        BeanUtils.copyProperties(salesPlanScItemStatSDO, planScItem);
        planScItem.setPlanId(Long.valueOf(salesPlanScItemStatSDO.getPlanId()));
        return planScItem;
    }

}
